/*
 * @lc app=leetcode.cn id=102 lang=cpp
 *
 * [102] 二叉树的层序遍历
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
    vector<vector<int>> levelOrder(TreeNode* root) {
        if(!root)
        {
            return vector<vector<int>>();
        }
        queue<pair<TreeNode*, int>> q;
        int depth = 0, last_depth = 0;
        q.push(make_pair(root, depth++));

        vector<vector<int>> ans;
        vector<int> v;
        while (!q.empty())
        {
            auto item = q.front();
            q.pop();
            if(item.second != last_depth)
            {
                last_depth = depth;
                depth++;
                ans.push_back(v);
                v.clear();
            }
            v.push_back(item.first->val);
            if(item.first->left)
            {
                q.push(make_pair(item.first->left, depth));
            }
            if(item.first->right)
            {
                q.push(make_pair(item.first->right, depth));
            }
        }
        if(v.size()) ans.push_back(v);
        return ans;
    }
};
// @lc code=end

